package com.charging.controller.admin;

import com.charging.entity.ChargingPile;
import com.charging.entity.FaultReport;
import com.charging.service.ChargingPileService;
import com.charging.service.FaultService;
import com.charging.service.RecordService;
import com.charging.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/admin/fault")
public class FaultController {

    @Autowired
    private UserService userService;

    @Autowired
    private ChargingPileService chargingPileService;

    @Autowired
    private FaultService faultService;

    @Autowired
    private RecordService recordService;

    // 列表页
    @GetMapping("/list")
    public String list(Model model) {
        List<FaultReport> faultsList = faultService.getAllFaults();
        model.addAttribute("faultsList", faultsList);
        List<ChargingPile> pileList = chargingPileService.findAll();
        model.addAttribute("pileList", pileList);
        return "admin/fault/list";
    }

    // 新增页
    @GetMapping("/add")
    public String showAddForm(Model model) {
        model.addAttribute("fault", new FaultReport());
        List<ChargingPile> pileList = chargingPileService.findAll();
        model.addAttribute("pileList", pileList);
        return "admin/fault/add";
    }

    @PostMapping("/add")
    public String add(FaultReport fault) {
        if (fault.getCreateTime() == null) {
            fault.setCreateTime(new Date()); // 或 LocalDateTime.now()
        }
        if (fault.getUpdateTime() == null) {
            fault.setUpdateTime(new Date()); // 或 LocalDateTime.now()
        }
        faultService.addFault(fault);
        return "admin/fault/list";
    }

    // 保存（新增/编辑）
    @GetMapping("/edit/{id}")
    public String editFaultForm(@PathVariable Long id, Model model) {
        FaultReport fault = faultService.getFaultById(id);
        model.addAttribute("fault", fault);
        return "admin/fault/edit";
    }

    @PostMapping("/edit")
    public String edit(@ModelAttribute FaultReport fault) {
        faultService.updateFault(fault);
        return "admin/fault/list";
    }


    @GetMapping("/detail/{id}")
    public String faultDetail(@PathVariable Long id, Model model) {
        model.addAttribute("fault", faultService.getFaultById(id));
        return "admin/fault/detail";
    }

    @GetMapping("/delete/{id}")
    public String delete(@PathVariable("id") Long id) {
        faultService.deleteFault(id);
        return "admin/fault/list";
    }
    
}
